import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  DatePicker,
  Radio,
  Empty,
  Typography,
  Divider,
} from 'antd';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import dayjs from 'dayjs';
import { getOrderTrend, getHotCourses } from '../../services/orders';
import useUser from '../../hooks/useUser';

const { Title } = Typography;
const { RangePicker } = DatePicker;

// 图表配色
const CHART_COLORS = ['#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#13c2c2'];
const PIE_COLORS = ['#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#faad14'];

const OrderAnalytics = () => {
  const { teacherId } = useUser();
  const [timeRange, setTimeRange] = useState([dayjs().subtract(30, 'day'), dayjs()]);
  const [trendPeriod, setTrendPeriod] = useState('day');
  const [trendData, setTrendData] = useState([]);
  const [hotCourses, setHotCourses] = useState([]);
  const [trendLoading, setTrendLoading] = useState(false);
  const [hotCoursesLoading, setHotCoursesLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('orders');

  // 获取销售趋势数据
  const fetchTrendData = async () => {
    if (!timeRange || !timeRange[0] || !timeRange[1]) return;
    
    setTrendLoading(true);
    try {
      const params = {
        teacherId,
        period: trendPeriod,
        dateFrom: timeRange[0].format('YYYY-MM-DD'),
        dateTo: timeRange[1].format('YYYY-MM-DD'),
      };
      
      const res = await getOrderTrend(params);
      
      // 处理数据，添加计算值
      const formattedData = res.data.map(item => ({
        ...item,
        net_amount: Number(item.sales_amount) - Number(item.refund_amount),
        conversion_rate: item.order_count > 0 
          ? ((item.paid_count / item.order_count) * 100).toFixed(2) 
          : 0,
      }));
      
      setTrendData(formattedData);
    } catch (error) {
      console.error('获取销售趋势数据失败:', error);
    } finally {
      setTrendLoading(false);
    }
  };
  
  // 获取热门课程数据
  const fetchHotCourses = async () => {
    if (!timeRange || !timeRange[0] || !timeRange[1]) return;
    
    setHotCoursesLoading(true);
    try {
      const params = {
        teacherId,
        limit: 8,
        dateFrom: timeRange[0].format('YYYY-MM-DD'),
        dateTo: timeRange[1].format('YYYY-MM-DD'),
      };
      
      const res = await getHotCourses(params);
      setHotCourses(res.data);
    } catch (error) {
      console.error('获取热门课程数据失败:', error);
    } finally {
      setHotCoursesLoading(false);
    }
  };
  
  // 初始加载和参数变化时获取数据
  useEffect(() => {
    if (teacherId) {
      fetchTrendData();
      fetchHotCourses();
    }
  }, [timeRange, trendPeriod, teacherId]);
  
  // 日期范围选择
  const handleRangeChange = (dates) => {
    setTimeRange(dates);
  };
  
  // 周期选择
  const handlePeriodChange = (e) => {
    setTrendPeriod(e.target.value);
  };
  
  // 格式化tooltips
  const formatTooltip = (value, name) => {
    if (name === 'conversion_rate') {
      return [`${value}%`, '转化率'];
    }
    
    if (name.includes('amount')) {
      return [`¥${value.toFixed(2)}`, name === 'sales_amount' ? '销售额' : 
              name === 'refund_amount' ? '退款额' : '净收入'];
    }
    
    switch (name) {
      case 'order_count':
        return [value, '订单数'];
      case 'paid_count':
        return [value, '支付数'];
      case 'refund_count':
        return [value, '退款数'];
      default:
        return [value, name];
    }
  };
  
  // 格式化图表标签
  const renderCustomAxisTick = ({ x, y, payload }) => {
    let label = payload.value;
    
    switch (trendPeriod) {
      case 'week':
        label = `W${label.split('-')[1]}`;
        break;
      case 'month':
        label = label.split('-')[1] + '月';
        break;
      case 'day':
        label = label.split('-')[2];
        break;
      default:
        break;
    }
    
    return (
      <text x={x} y={y + 10} textAnchor="middle" fill="#666">
        {label}
      </text>
    );
  };
  
  return (
    <div className="order-analytics">
      <div className="chart-container">
        {activeTab === 'orders' && (
          <Card 
            title={
              <div className="analytics-header">
                <Title level={4}>订单量与转化率趋势</Title>
                <div className="time-filter">
                  <RangePicker
                    value={timeRange}
                    onChange={handleRangeChange}
                    allowClear={false}
                    style={{ marginRight: 16 }}
                  />
                  <Radio.Group value={trendPeriod} onChange={handlePeriodChange}>
                    <Radio.Button value="day">日</Radio.Button>
                    <Radio.Button value="week">周</Radio.Button>
                    <Radio.Button value="month">月</Radio.Button>
                  </Radio.Group>
                </div>
              </div>
            }
            bordered={false} 
            className="chart-card"
            loading={trendLoading}
            extra={
              <Radio.Group value={activeTab} onChange={(e) => setActiveTab(e.target.value)}>
                <Radio.Button value="orders">订单与转化率</Radio.Button>
                <Radio.Button value="sales">销售与退款</Radio.Button>
                <Radio.Button value="courses">热门课程</Radio.Button>
              </Radio.Group>
            }
          >
            {trendData.length > 0 ? (
              <ResponsiveContainer width="100%" height={400}>
                <LineChart
                  data={trendData}
                  margin={{ top: 20, right: 30, left: 20, bottom: 20 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date_group" tick={renderCustomAxisTick} />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" domain={[0, 100]} />
                  <Tooltip formatter={formatTooltip} />
                  <Legend />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="order_count"
                    name="订单数"
                    stroke={CHART_COLORS[0]}
                    activeDot={{ r: 6 }}
                    strokeWidth={2}
                  />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="paid_count"
                    name="已支付"
                    stroke={CHART_COLORS[1]}
                    activeDot={{ r: 5 }}
                    strokeWidth={2}
                  />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="refund_count"
                    name="已退款"
                    stroke={CHART_COLORS[3]}
                    activeDot={{ r: 5 }}
                    strokeWidth={2}
                  />
                  <Line
                    yAxisId="right"
                    type="monotone"
                    dataKey="conversion_rate"
                    name="转化率"
                    stroke={CHART_COLORS[2]}
                    strokeDasharray="5 5"
                    dot={{ r: 4 }}
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <Empty description="暂无数据" />
            )}
          </Card>
        )}
        
        {activeTab === 'sales' && (
          <Card 
            title={
              <div className="analytics-header">
                <Title level={4}>销售额与退款趋势</Title>
                <div className="time-filter">
                  <RangePicker
                    value={timeRange}
                    onChange={handleRangeChange}
                    allowClear={false}
                    style={{ marginRight: 16 }}
                  />
                  <Radio.Group value={trendPeriod} onChange={handlePeriodChange}>
                    <Radio.Button value="day">日</Radio.Button>
                    <Radio.Button value="week">周</Radio.Button>
                    <Radio.Button value="month">月</Radio.Button>
                  </Radio.Group>
                </div>
              </div>
            }
            bordered={false} 
            className="chart-card"
            loading={trendLoading}
            extra={
              <Radio.Group value={activeTab} onChange={(e) => setActiveTab(e.target.value)}>
                <Radio.Button value="orders">订单与转化率</Radio.Button>
                <Radio.Button value="sales">销售与退款</Radio.Button>
                <Radio.Button value="courses">热门课程</Radio.Button>
              </Radio.Group>
            }
          >
            {trendData.length > 0 ? (
              <ResponsiveContainer width="100%" height={400}>
                <BarChart
                  data={trendData}
                  margin={{ top: 20, right: 30, left: 20, bottom: 20 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date_group" tick={renderCustomAxisTick} />
                  <YAxis />
                  <Tooltip formatter={formatTooltip} />
                  <Legend />
                  <Bar 
                    dataKey="sales_amount" 
                    name="销售额" 
                    fill={CHART_COLORS[0]} 
                    stackId="a"
                  />
                  <Bar 
                    dataKey="refund_amount" 
                    name="退款额" 
                    fill={CHART_COLORS[3]} 
                    stackId="b"
                  />
                  <Line
                    type="monotone"
                    dataKey="net_amount"
                    name="净收入"
                    stroke={CHART_COLORS[4]}
                    strokeWidth={2}
                    dot={{ r: 4 }}
                  />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <Empty description="暂无数据" />
            )}
          </Card>
        )}
        
        {activeTab === 'courses' && (
          <Card 
            title={
              <div className="analytics-header">
                <Title level={4}>热门课程订单分布</Title>
                <div className="time-filter">
                  <RangePicker
                    value={timeRange}
                    onChange={handleRangeChange}
                    allowClear={false}
                    style={{ marginRight: 16 }}
                  />
                </div>
              </div>
            }
            bordered={false} 
            className="chart-card"
            loading={hotCoursesLoading}
            extra={
              <Radio.Group value={activeTab} onChange={(e) => setActiveTab(e.target.value)}>
                <Radio.Button value="orders">订单与转化率</Radio.Button>
                <Radio.Button value="sales">销售与退款</Radio.Button>
                <Radio.Button value="courses">热门课程</Radio.Button>
              </Radio.Group>
            }
          >
            {hotCourses.length > 0 ? (
              <Row gutter={[24, 24]}>
                <Col xs={24} lg={12}>
                  <ResponsiveContainer width="100%" height={300}>
                    <PieChart>
                      <Pie
                        data={hotCourses.map(course => ({
                          name: course.course_title,
                          value: Number(course.order_count),
                          amount: Number(course.total_amount),
                        }))}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        outerRadius={80}
                        fill="#8884d8"
                        dataKey="value"
                        nameKey="name"
                        label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(1)}%`}
                      >
                        {hotCourses.map((_, index) => (
                          <Cell key={`cell-${index}`} fill={PIE_COLORS[index % PIE_COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip 
                        formatter={(value, name) => [`${value} 订单`, name]}
                        itemStyle={{ color: '#333' }}
                      />
                    </PieChart>
                  </ResponsiveContainer>
                </Col>
                <Col xs={24} lg={12}>
                  <Title level={5}>热门课程排名</Title>
                  <Divider style={{ margin: '12px 0' }} />
                  <div className="hot-courses-list">
                    {hotCourses.map((course, index) => (
                      <div key={course.course_id} className="hot-course-item">
                        <div className="course-rank">
                          <span className={`rank-badge ${index < 3 ? 'top-rank' : ''}`}>
                            {index + 1}
                          </span>
                          <span className="course-name">{course.course_title}</span>
                        </div>
                        <div className="course-data">
                          <span className="order-count">{course.order_count}订单</span>
                          <span className="amount">¥{Number(course.total_amount).toFixed(2)}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </Col>
              </Row>
            ) : (
              <Empty description="暂无数据" />
            )}
          </Card>
        )}
      </div>
    </div>
  );
};

export default OrderAnalytics;